package com.vehicle.repair.service;

import com.vehicle.repair.model.Repairer;
import com.vehicle.repair.model.User;
import com.vehicle.repair.repository.RepairerRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class RepairerService {
    private final RepairerRepository repairerRepository;
    private final UserService userService;

    public RepairerService(RepairerRepository repairerRepository, UserService userService) {
        this.repairerRepository = repairerRepository;
        this.userService = userService;
    }

    public Repairer registerRepairer(Repairer repairer, Integer userId) {
        User user = userService.getUserById(userId)
                .orElseThrow(() -> new IllegalArgumentException("User not found"));
        
        if (repairerRepository.existsByUser_Username(user.getUsername())) {
            throw new IllegalArgumentException("User already registered as repairer");
        }
        
        repairer.setUser(user);
        return repairerRepository.save(repairer);
    }

    public Optional<Repairer> getRepairerById(Integer id) {
        return repairerRepository.findById(id);
    }

    public List<Repairer> getRepairersBySkillType(Repairer.SkillType skillType) {
        return repairerRepository.findBySkillType(skillType);
    }

    public Repairer updateRepairer(Repairer repairer) {
        return repairerRepository.save(repairer);
    }

    public void deleteRepairer(Integer id) {
        repairerRepository.deleteById(id);
    }
}
